<template>
  <div class="container">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="form">
      <el-form-item label="头像" prop="userAvatar">
        <img :src="form.userAvatar" class="user-avatar">
        <el-upload
          class="upload-demo"
          action
          :before-upload="beforeAvatarUpload"
          :http-request="handleUpload"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :before-remove="beforeRemove"
          multiple
          :limit="limit"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :list-type="listType"
        >
          <el-button size="small" type="primary" style="width: 180px">点击上传(.jpg/.png/.jpeg)</el-button>
          <div slot="tip" class="el-upload__tip">{{ tip }}</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="账号" prop="userAccount">
        <el-input v-model="form.userAccount" placeholder="请输入用户账号"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="form.userName" placeholder="请输入用户姓名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="userPasswd">
        <el-input type="password" v-model="form.userPasswd" placeholder="请输入用户密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="籍贯" prop="userPlace">
        <el-input v-model="form.userPlace" placeholder="请输入用户籍贯"></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="userTel">
        <el-input v-model="form.userTel" placeholder="请输入手机号码"></el-input>
      </el-form-item>
      <el-form-item label="电子邮箱" prop="userEmail">
        <el-input v-model="form.userEmail" placeholder="请输入电子邮箱"></el-input>
      </el-form-item>
      <el-form-item label="出生日期" prop="userBirth">
        <el-date-picker
          v-model="form.userBirth"
          prop="userBirth"
          type="date"
          placeholder="选择出生日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {getUserInfo, userEdit} from '@/api/user'
import { v4 as uuidv4 } from 'uuid';
import {put} from '@/ali-oss'

export default {
  props: {
    tip: {
      type: String,
      // default: '上传大小不能超过20M'
    },
    limit: {
      type: Number,
      default: 1
    },
    action: {
      type: String,
      default: ''
    },
    headers: {
      type: Object,
      default: () => {}
    },
    name: {
      type: String,
      default: ''
    },
    listType: {
      type: String,
      default: 'text'
    }
  },
  data() {
    return {
      fileList: [],
      form: {
        userId: this.$route.params.userId,
        userAccount: '',
        userName: '',
        userPasswd: '',
        userPlace: '',
        userTel: '',
        userEmail: '',
        userBirth: '',
        userAvatar: ''
      },
      rules: {
        userAccount: [
          {required: true, message: '请输入用户账号', trigger: 'change'}
        ],
        userName: [
          {required: true, message: '请输入用户姓名', trigger: 'change'}
        ],
        userPasswd: [
          {required: true, message: '请输入用户密码', trigger: 'change'}
        ],
        userHidden: [
          {required: true, trigger: 'change'}
        ],
      }
    }
  },
  created() {
    this.getInfo()
  },
  methods: {
    handleRemove(file, fileList) {
      this.$emit('on-remove', file, fileList)
    },
    handlePreview(file) {
      this.$emit('on-preview', file)
    },
    beforeAvatarUpload:function(file){
      // 上传前的操作
      if (!(file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
        this.$message.warning('请上传正确格式的图片');
      }
      const size = file.size / 1024 / 1024
      if (size > 16) {
        this.$message.warning('图片大小必须小于16M');
        return false;
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`只能上传 ${this.limit} 个图片,请移除其余图片`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleSuccess(response, file, fileList) {
      this.fileList = fileList
      this.$emit('on-success', file, fileList)
    },
    /**
     * 自定义上传方法
     */
    handleUpload(option) {
      // 生成的文件名称
      let objName = uuidv4()

      // 调用 ali-oss 中的方法
      put(`avatar/${objName}`, option.file).then(res => {
        console.log(res)
        this.form.userAvatar=res.url
      })
    },
    getInfo() {
      getUserInfo({userId: this.form.userId}).then(res=>{
        this.form = res.data
        console.log(this.form)
        this.form.userPasswd = this.$route.params.password
      })
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // console.log(this.form)
          userEdit(this.form).then(res => {
            if (res.data != null) {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              localStorage.removeItem('userInfo')
              localStorage.setItem('userInfo', JSON.stringify(res.data))
              this.$router.push({name: 'Dashboard'})
            } else {
              this.$message({
                message: '修改失败',
                type: 'error'
              })
            }
          })
        }
      })
    },
    onCancel() {
      this.$router.push({name: 'Dashboard'})
    }
  }
}
</script>
<style lang="scss">
.container {
  padding: 50px;
  display: flex;
  justify-content: center;

  .form {
    width: 700px;
  }

  .user-avatar {
    object-fit: cover;
    width: 180px;
    height: 180px;
    border-radius: 10px;
  }
}
</style>
